package com.slt.linux.util;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
 
/**
 * @Author: 
 * @Date: 
 * excel导出工具类,这里是直接通过response的方式返回我们创建好的excel对象。
 *  这样的话是直接通过网页的方式直接下载返回文件的。
 */
public class ExportExcelUtil<T extends BaseRowModel> {
 
    public ExportExcelUtil() {}
 
    /**
     * 导出excel表格
     */
//    public void exportExcel(HttpServletResponse response, List<T> data, Class<T> clazz, String fileName) throws IOException {
//        response.reset();
//        response.setContentType("application/vnd.ms-excel");
//        // 注意，这里filename*=utf-8''是为了避免导出的文件名乱码！！！
//        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
//        OutputStream out = null;
//        try {
//            out = response.getOutputStream();
//            //ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
//            StyleExcelHandler handler = new StyleExcelHandler();
//            //ExcelWriter writer = new ExcelWriter(null,out, ExcelTypeEnum.XLSX,true);
//            ExcelWriter writer = new ExcelWriter(null,out, ExcelTypeEnum.XLSX,true,handler);
//            Sheet sheet1 = new Sheet(1, 0, clazz);
//            sheet1.setSheetName("sheet1");
//            writer.write(data, sheet1);
//            writer.finish();
//        } finally {
//            if (out != null) {
//                out.close();
//            }
//        }
//    }
 
    public void createExcel(ByteArrayOutputStream out,List<T> data, Class<T> clazz) throws IOException{
        try {
            //StyleExcelHandler handler = new StyleExcelHandler();
            ExcelWriter writer = new ExcelWriter(null,out, ExcelTypeEnum.XLSX,true);
            Sheet sheet1 = new Sheet(1, 0, clazz);
            sheet1.setSheetName("在线咨询数据分析表");
            writer.write(data, sheet1);
            writer.finish();
        }
        finally {
            if (out != null) {
                out.close();
            }
        }
    }
}